import { ExceptionFilter, Catch, ArgumentsHost } from "@nestjs/common";
import { Response } from "express";
import { EntityNotFoundError } from "typeorm";

@Catch(EntityNotFoundError)
export class NotFoundFilter implements ExceptionFilter {
  catch(exception: EntityNotFoundError, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const target = exception.message
      .split('Could not find any entity of type "')[1]
      .split('" matching: ')[0];
    const condition = exception.message.split('" matching: ')[1];

    response.status(404).json({
      statusCode: 404,
      target,
      condition,
      message: "找不到对象",
    });
  }
}
